import * as THREE from "../../node_modules/three/build/three.module.js"
// import {OrbitControls} from "../../node_modules/three/examples/jsm/controls/OrbitControls.js";
import {OrbitControls} from "./m__OrbitControls.js";

let scene, camera, renderer, texture, item;
let canvas, ctx, img2;
let isPainting = false , mousePos = new THREE.Vector2(), raycaster;

init();
animate();
function init(){
    (function initThree(){
        let width = innerWidth/2;
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera(50, width/window.innerHeight, 0.01, 1000);
        renderer = new THREE.WebGLRenderer();

        camera.position.z = 10;
        renderer.setSize(width, window.innerHeight);
        renderer.setClearColor(0xcccccc);
        document.body.appendChild(renderer.domElement);
        new OrbitControls(camera, renderer.domElement);
    })();


    (function initCanvas(){
        canvas = document.createElement('canvas');
        canvas.width = 2**9;
        canvas.height = 2**9;
        document.body.appendChild(canvas);
        ctx = canvas.getContext('2d');
        let img = new Image();
        img.src = `./pic1.jpg`;
        img2 = new Image();
        img2.src = `./decal-diffuse.png`;

        img.onload=function(){
            // ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
            ctx.fillRect(0,0,canvas.width,canvas.height);

            texture.image = canvas;
            texture.needsUpdate = true;
        }
    })();


    (function initScene(){
        // let picLoader = new THREE.TextureLoader();
        // texture = picLoader.load('./pic1.jpg',
        //     function(texture){
        //         // texture.wrapS = THREE.ClampToEdgeWrapping;
        //         // texture.wrapS = THREE.RepeatWrapping;
        //         // texture.wrapS = THREE.MirroredRepeatWrapping;
        //         // texture.wrapT = THREE.MirroredRepeatWrapping;
        //         texture.repeat.set(2,3);
        //         texture.offset.set(-.5,-1)
        //     }
        // );

        // texture = new THREE.Texture( undefined, THREE.UVMapping, THREE.RepeatWrapping, THREE.RepeatWrapping );
        texture = new THREE.Texture( undefined, THREE.NearestFilter, THREE.RepeatWrapping, THREE.RepeatWrapping );
        texture.image = canvas;

        let box = new THREE.Group();
        let planeG = new THREE.PlaneBufferGeometry(10,10,10);
        let planeM = new THREE.MeshBasicMaterial({
            color: 0x000000
        });
        let meshUnder = new THREE.Mesh(planeG, planeM);
        meshUnder.position.y = -5;
        meshUnder.rotation.x = - Math.PI / 2.;
        let meshUp = new THREE.Mesh(planeG, planeM);
        meshUp.position.y = 5;
        meshUp.rotation.x = Math.PI / 2.;
        let meshFront = new THREE.Mesh(planeG, planeM);
        meshFront.position.z = -5;
        let meshBehind = new THREE.Mesh(planeG, planeM);
        meshBehind.position.z = 5;
        meshBehind.rotation.x = Math.PI;
        let meshLeft = new THREE.Mesh(planeG, planeM);
        meshLeft.position.x = -5;
        meshLeft.rotation.y = Math.PI / 2.;
        let meshRight = new THREE.Mesh(planeG, planeM);
        meshRight.position.x = 5;
        meshRight.rotation.y = -Math.PI / 2.;
        
        box.add(meshUnder, meshUp, meshFront, meshBehind, meshLeft, meshRight);
        scene.add(box);


        // texture.needsUpdate= true;
        let g;// = new THREE.SphereBufferGeometry(1,20,20);
        let ran = Math.floor(Math.random() * 7);
        console.log(ran);
        switch(ran){
            case 0 : g = new THREE.BoxBufferGeometry(); break;
            case 1 : g = new THREE.SphereBufferGeometry(1,20,20); break;
            case 2 : g = new THREE.ConeBufferGeometry(); break;
            case 3 : g = new THREE.CylinderBufferGeometry(); break;
            case 4 : g = new THREE.ParametricBufferGeometry(); break;
            case 5 : g = new THREE.RingBufferGeometry(); break;
            case 6 : g = new THREE.TorusKnotBufferGeometry(); break;
            case 7 : g = new THREE.TubeBufferGeometry(); break;
            default : g = new THREE.TorusBufferGeometry(); break;
        }
        // let g = new THREE.BoxBufferGeometry();
        let mat = new THREE.MeshLambertMaterial({
            map: texture
        })

        item = new THREE.Mesh(g, mat);
        item.scale.set(3,3,3);
        item.name = "the cube";
        scene.add(item);


        let light = new THREE.PointLight(0xffffff, 2, 100);
        light.position.set(17,17,17);
        scene.add(light);
        let light2 = new THREE.PointLight(0xffffff, 2, 100);
        light2.position.set(-17,-17,-17);
        // scene.add(light2);

        let lightA = new THREE.AmbientLight(0xffffff,.3);
        scene.add(lightA);

    })();

    initRay();
    function initRay(){
        raycaster = new THREE.Raycaster();
        var onClickPosition = new THREE.Vector2();

        renderer.domElement.addEventListener(`mousedown` , function(e){
            // console.log(e);
            if(e.button != 0) return; // 如果不是左击, 直接跳出
            let rendererSize=renderer.getSize();
            
            mousePos.set(e.offsetX/rendererSize.x-.5, -(e.offsetY/rendererSize.y-.5));
            mousePos.x *= 2;
            mousePos.y *= 2;
            console.log(mousePos.x, mousePos.y);

            raycaster.setFromCamera( mousePos, camera );
            let i = raycaster.intersectObjects( item );
            console.log(i);

            if(i.length){
                console.log(`uv`,i[0].uv);
                draw(i[0].uv.x*canvas.width,(1-i[0].uv.y)*canvas.height)
            }
            isPainting = true;
        });

        renderer.domElement.addEventListener(`mousemove`,function(e){
            if(isPainting){
                let rendererSize = renderer.getSize();
                mousePos.set(e.offsetX/rendererSize.x-.5, -(e.offsetY/rendererSize.y-.5));
                mousePos.x *= 2;
                mousePos.y *= 2;
            }
        });

        renderer.domElement.addEventListener(`mouseup` , function(e){
            isPainting = false;
        });
        

        // raycaster.setFromCamera( mouse, camera );
        // raycaster.intersectObjects( objects );
    }

}
function draw(x,y){
    // console.log(ctx);
    ctx.translate(x,y);
    let angle = Math.random()*2*Math.PI;
    ctx.rotate(angle);
    let size = canvas.width/20;
    ctx.drawImage(img2,0,0,img2.width,img2.height,-size/2,-size/2,size,size);
    // size = size / (Math.random() + 1);
    ctx.drawImage(img2,0,0,img2.width,img2.height,-size/2+Math.random()*10,-size/2+Math.random()*10,size,size);
    ctx.drawImage(img2,0,0,img2.width,img2.height,-size/2+Math.random()*20,-size/2+Math.random()*20,size,size);
    ctx.drawImage(img2,0,0,img2.width,img2.height,-size/2+Math.random()*20,-size/2+Math.random()*20,size,size);
    ctx.rotate(-angle);
    ctx.translate(-x,-y);
    texture.needsUpdate = true;
}



canvas.onclick = function(e){
    console.log(e);
    draw(e.offsetX, e.offsetY);
}
canvas.addEventListener(`mousedown`, function(e){
    console.log(`mousedown`,e);
})

function animate(){
    requestAnimationFrame(animate);
    
    if(isPainting){
        raycaster.setFromCamera( mousePos, camera );
        let i = raycaster.intersectObjects( scene.children );
        console.log(i);

        if(i.length){
            console.log(`uv`,i[0].uv);
            draw(i[0].uv.x*canvas.width,(1-i[0].uv.y)*canvas.height)
        }
    }

    renderer.render(scene,camera);
}

window.scene = scene;
window.camera = camera;
window.renderer = renderer;
window.canvas = canvas;
window.ctx = ctx;
window.draw = draw;